$(document).ready(function(){
	//租借充电宝金额
	var borrowCDBMoney = 0;
	//购线金额
	var buyLineMoney = 0;
	//是否有足够资格购线或者租借充电宝
	var isEnough = -1;
	//如果用户没有足够的金额，相差金额是多少
	var shortMoney = 0;
	//提示用户的信息
	var popMessage = "";
	//提示用户的标题
	var popTitle = "";
	//租借或者购线成功后查询任务的Id
	var taskId = 0;
	//设备号
	var device = "";
	//循环查询任务
	var forSelectTask = undefined;
	//循环查询用户信息
	var forSelectUser = undefined;
	//是否享有免费购线券
	var presentLineBuyCnt = undefined;
	//用户金额
	var money = undefined;
	//查询用户接口类型
	var getUserType = undefined;

	var requestTime = 0;

	var isInborrowByLine = 0;
	//选购数据线类型
	var lineType = 0;

	var ticket = undefined;

	var preMoney = undefined;

	var presentMoneyTimes = 2;

	var isPrePay = undefined;

	var payTypeIsAvailable = undefined;

	var checkLineAndCDBRequestTime = undefined;

	access_token = $.getCookie("access_token");

	if($('.access_token').val() != "" && $('.access_token').val() != null){
		access_token = $('.access_token').val();
		if($.getCookie("access_token") == null){
			$.setCookie("access_token", access_token);
		}		
	}
	//查询购买记录
	$.selectTask = function(){
		//判断循环访问时间是否超过30秒
		
		if(requestTime >= 17){
			//停止循环访问任务接口
			clearInterval(forSelectTask);
			$.popTagShow(4,'网络错误请重新扫描',null,null,null,null,null,"知道了",$.popTagHide2);	
			//充值超时访问时间
			requestTime=0;
			return false;
		}
		//叠加访问接口次数
		requestTime = requestTime+1;
		//访问获取任务处理结果接口
		$.getJSON("/"+server+"/taskGet?access_token="+access_token+"&taskId="+taskId+requestLast,function(json){
			//如果返回结果是租借成功
			if(json.taskModel.status == 1){
				//停止循环访问任务
				clearInterval(forSelectTask);	
				//如果用户正在租借充电宝
				if(isInborrowByLine == 0 && json.taskModel.popType == 0){
					//如果用户第一次充值，或者拥有免费购线机会
					if(presentLineBuyCnt > 0){
						//展示购线选择
						$('.buy-line').show();
						$('.charge-borrow').hide();
						$.popTagHide();
						if(ticket.type != undefined && ticket.type != null){
							$('.buy-line .discount').show();
							if(ticket.type.discount > 0){
								$('.buy-line .discount .discount-text').text(parseInt(ticket.type.discount*10)+"折");
								$('.buy-line .discount .discount-text').css('right','18%');
							}
							else{
								$('.buy-line .discount .discount-text').text("免费");
								$('.buy-line .discount .discount-text').css('right','22%');
							}
						}
						else{
							$('.buy-line .discount').hide();
						}
					}
					else if(presentMoneyTimes == 0){
						$('.buy-line').show();
						$('.charge-borrow').hide();
						$.popTagHide();
						$('.buy-line .discount').hide();
					}		
					else{
						//直接提示用户租借成功
						$.popTagShow(3,'租借成功',null,null,null,null,null,null,null);		
						setTimeout("wx.closeWindow()",5000);
					}
				}
				//购买数据线提示
				else if(isInborrowByLine == 1  && json.taskModel.popType == 0){
					//提示用户购线成功
					$.popTagShow(3,'购买成功',null,null,null,null,null,null,null);	
					setTimeout("wx.closeWindow()",5000);				
				}
				else if(json.taskModel.popType != 0){
					if(json.isNotHaveLine == 1){
						$.popTagShow(1,json.taskModel.popMessage,"",null,null,null,null,"确定",$.popTagHide2);	
					}
					else{
						$.popTagShow(4,json.taskModel.popMessage+",请重新扫描",null,null,null,null,null,"确定",$.popTagHide2);		
					}	
				}
				requestTime=0;
				getUserType = 1;
				$.selectUser();
			}
			else if(json.taskModel.popType == 1){
				clearInterval(forSelectTask);	
				$.popTagShow(4,json.taskModel.popMessage+",请重新扫描",null,null,null,null,null,"确定",$.popTagHide2);		
				requestTime=0;
			}			
		})
	}	

	//租借充电宝
	$.taskAdd = function(){
				$.getJSON("/"+server+"/taskAdd?access_token="+access_token+"&terminal="+device+"&requestTime="+checkLineAndCDBRequestTime+requestLast,function(json){
					if(json.result == 1){
					    taskId = json.taskId
						$.popTagShow(2,'请留意机器屏幕信息','正在处理，请等待！',null,null,null,null,null,null);				    
						//循环查询租借任务处理结果	
					    forSelectTask = window.setInterval("$.selectTask()",2000);
					}
					else{	    
			    		$.popTagShow(4,json.msg,null,null,null,null,null,"知道了",$.popTagHide2);	
					}
				}); 		
	}		

	//查询用户信息
	$.selectUser = function(){
		$.getJSON("/"+server+"/UserGet?access_token="+access_token+requestLast,function(json){
 			//记录用户是否拥有免费购线机会		
 			presentLineBuyCnt = json.user.cnt.presentLineBuyCnt;
 			ticket = json.user.ticket;
 			preMoney = json.user.preMoney;

 			if(json.user.money == 0){
 				presentMoneyTimes = json.user.presentMoneyTimes;
 			}
 			// alert(presentMoneyTimes)
 			// alert(ticket.type.discount);
 			//判断服务器返回用户金额是否与用户之前的金额不同
			if(money != parseInt(json.user.money) && getUserType == 0){
				//停止循环访问用户信息接口
				clearInterval(forSelectUser);
				//记录下用户金额
				money = parseInt(json.user.money);
				//判断用户充值之后是进行购线或者租借充电宝
				if(lineType == 0){
					$.taskAdd();
				}
				else{
					$.taskAddBuyLine();	
				}
			}
			//刷新用户金额等信息
			else if(getUserType == 1){
				//记录下用户金额
				money = parseInt(json.user.money);
			}
		})
	}	

	// $.selectUser();

	//拉起支付
	$.prepaid = function(){
						if(payTypeIsAvailable != 1){
							$.popTagShow(1,'微信支付暂不可用','请稍后再尝试',null,null,null,null,"确定",$.popTagHide);
							return false;
						}
			            //获取支付JSON数据
			            $.getJSON("/"+server+"/chargeCreate?access_token="+access_token+"&channel=wx_pub&amount="+shortMoney+requestLast,function(json){
									$.popTagShow(2,'正在支付','正在支付请稍后',null,null,null,null,null,null);	
				                    pingpp.createPayment(json, function(result, err) {
				                    	if(result == "success"){
				                    		getUserType = 0;
				                    		//充值成功后循环查询用户金额
				                    		forSelectUser = window.setInterval("$.selectUser()",2000);
				                    		//弹出充电宝出仓中提示
				                    		$.popTagShow(2,'请留意机器屏幕信息','正在处理，请等待！',null,null,null,null,null,null);
							    		}
									    else if (result == "fail") {
											$.popTagShow(1,'支付失败','请重试',null,null,null,null,"好的",$.popTagHide);				    			    	
									    } 
									    else if (result == "cancel") {
									    	$.popTagShow(1,'取消支付','你取消了支付',null,null,null,null,"好的",$.popTagHide);	
									    }						    					                        
				                    });	
			           });	
	}



	$('.charge-button').click(function(){
		$.prepaid();
	});

	$('.borrow-button').click(function(){
		$.taskAdd();
	});	

	//点击扫码
	$.scan = function(){
		// alert("scan");
		// getUserType = 1;
		getUserType = 1;
		$.selectUser();		
		wx.scanQRCode({
		    needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
		    scanType: ["qrCode"], // 可以指定扫二维码还是一维码，默认二者都有
		    success: function (res) {
		    	$.popTagHide();
		    	var result = res.resultStr; // 当needResult 为 1 时，扫码返回的结果
		    	//存储返回设备号
		    	device = getQueryString(result,"qrcode");
				$.getJSON("/"+server+"/deviceCheckLineAndCDB?access_token="+access_token+"&terminal="+device+"&type=1"+requestLast,function(json){
						if(json.result == 1){						
	    					//设置充电宝押金
							borrowCDBMoney = parseFloat(json.deviceCharge.borrowCDBMoney)*100;
							//设置购线金额
							buyLineMoney = parseFloat(json.deviceCharge.buyLinePay)*100;	
							//用户是否有足够金额购买
							isEnough = 	parseFloat(json.isEnough);
							//设置用户应该充值多少钱用于租借或者购线
							shortMoney = parseFloat(json.shortMoney);						
							//设置提示框信息
							popMessage = json.popMessage;
							//设置提示框标题
							popTitle = json.popTitle;
							//设置请求任务时间戳
							checkLineAndCDBRequestTime = json.requestTime;
							//设置设备收费信息
							$('.shortMoney').show();
                            $('.borrow-pay-title').show();
                            $('.gratis-time').show();
                            $('.vip-gratis-time').show();							
							$('.shortMoney').text("需支付押金："+(shortMoney/100)+"元");
							$('.money').text("来电账户："+money+"元");
							$('.preMoney').text("充电宝押金"+json.deviceCharge.borrowCDBMoney+"元");
							$('.borrow-pay-title').text(json.deviceCharge.borrowPayTitle);
							$('.hour-pay-title').text(json.deviceCharge.hourPayTitle);
							$('.max-pay-title').text(json.deviceCharge.maxPayTitle);
                            $('.gratis-time').text(json.deviceCharge.gratisTimeStr);
                            $('.hour-pay').text(json.deviceCharge.hourPayStr);
                            $('.max-pay').text(json.deviceCharge.dayMaxPayStr);
                            $('.vip-gratis-time').text(json.deviceCharge.vipGratisTimeStr);
                            $('.vip-hour-pay').text(json.deviceCharge.vipHourPayStr);
                            $('.vip-max-pay').text(json.deviceCharge.vipDayMaxPayStr);							
                            $('.annotation').text(json.deviceCharge.annotation);

                            $('.buy-line .title .font1').text("数据线"+buyLineMoney/100+"元/条");

                            if(json.deviceCharge.borrowPayTitle == ""){
                            	$('.borrow-pay-title').hide();
                            	$('.gratis-time').hide();
                            	$('.vip-gratis-time').hide();
                            }
							//如果类型为高收费模式弹出提示
							if(isEnough == 1){
	                            if(json.deviceCharge.chargeType == 2){
	                            	$('.shortMoney').hide();
	                            	$('hr').hide();
	                            	$('.charge-borrow').show();
	                            	$('.charge-button').hide();
	                            	$('.borrow-button').show();
	                            	$('.charge-borrow .content').show();
							    }
							    else{
									$.taskAdd();
							    }
							}	
							else if(isEnough == 0){
								$('hr').show();
	                            $('.charge-borrow').show();
	                            $('.charge-button').show();
	                            $('.borrow-button').hide();									
								if(json.deviceCharge.chargeType == 2){
	                            	$('.charge-borrow .content').show();
	                            }
	                            else{
	                            	$('.charge-borrow .content').hide();                            	
	                            }						
							}

							for(var i=0;i<json.payType.length;i++){
								if(json.payType[i].payType==1){
									payTypeIsAvailable = json.payType[i].isAvailable;
								}
							}
						}
						else{
							$.popTagShow(5,json.msg,null,"取消",wx.closeWindow,"前往附近",function(){window.location.href="/"+server+"/nearbyShop"},null,null);
						}
					})		    		    
			},
			fail:function(res){
				$.popTagShow(4,'网络错误请重新扫描',null,null,null,null,null,"知道了",$.popTagHide2);
			}
		});	
	};


	//购买充电线
	$.taskAddBuyLine = function(){
				// alert("buyline");
				$.getJSON("/"+server+"/taskAddBuyLine?access_token="+access_token+"&terminal="+device+"&lineType="+lineType+"&requestTime="+checkLineAndCDBRequestTime+requestLast,function(json){
					if(json.result == 1){
					    taskId = json.taskId
					    isInborrowByLine = 1;
						$.popTagShow(2,'请查看机器是否吐出充电线','正在响应',null,null,null,null,null,null);				    
						//循环查询租借任务处理结果	
					    forSelectTask = window.setInterval("$.selectTask()",2000);
					}
					else{	    
			    		$.popTagShow(4,json.msg,null,null,null,null,null,"知道了",$.popTagHide);	
					}					
				}); 				
	}

	$.checkLine = function(){
		$.getJSON("/"+server+"/deviceCheckLineAndCDB?access_token="+access_token+"&terminal="+device+"&type=2&lineType="+lineType+requestLast,function(json){
				if(json.result == 1){
		    		//设置充电宝押金
					borrowCDBMoney = parseFloat(json.deviceCharge.borrowCDBMoney)*100;
					//设置购线金额
					buyLineMoney = parseFloat(json.deviceCharge.buyLinePay)*100;	
					//用户是否有足够金额购买
					isEnough = 	parseFloat(json.isEnough);
					//设置用户应该充值多少钱用于租借或者购线
					shortMoney = parseFloat(json.shortMoney);						
					//设置提示框信息
					popMessage = json.popMessage;
					//设置提示框标题
					popTitle = json.popTitle;
					//设置是否押金支付
					isPrePay = json.isPrePay;
					//设置请求任务时间戳
					checkLineAndCDBRequestTime = requestTime;					
					//设置设备收费信息
					if(isEnough == 1){
						if(ticket.type != undefined && ticket.type != null){
							if(ticket.type.discount > 0){
								if(preMoney >= 100){
									$.popTagShow(1,popMessage,popTitle,"重选",$.popTagHide,"押金支付",$.taskAddBuyLine,null,null);
								}
								else{
									$.popTagShow(1,popMessage,popTitle,"重选",$.popTagHide,"余额支付",$.taskAddBuyLine,null,null);	
								}
							}
							else{
								$.popTagShow(1,popMessage,popTitle,"重选",$.popTagHide,"确定",$.taskAddBuyLine,null,null);
							}
						}
						else if(isPrePay == 1){
							$.popTagShow(1,popMessage,popTitle,"重选",$.popTagHide,"押金支付",$.taskAddBuyLine,null,null);
						}
						else{
	                    	$.popTagShow(1,popMessage,popTitle,"重选",$.popTagHide,"确定",$.taskAddBuyLine,null,null);
	                    }
					}	
					else if(isEnough == 0){
						$.popTagShow(1,popMessage,popTitle,"重选",$.popTagHide,"支付",$.prepaid,null,null);							
					}		
				}
				else{
					if(json.isNotHaveLine == 1){
						$.popTagShow(1,json.msg,"","取消",wx.closeWindow,"前往附近",function(){window.location.href="/"+server+"/nearbyShop"},null,null);
					}
					else{
						$.popTagShow(5,json.msg,null,"取消",wx.closeWindow,"前往附近",function(){window.location.href="/"+server+"/nearbyShop"},null,null);
					}
				}			
		})		
	}

	$('.type-c').click(function(){
		$.popTagShow(1,"暂时不提供type-c数据线",'请重新选择',null,null,null,null,"知道啦！",$.popTagHide);
	})
	//买iphone4线
	$('.iphone4').click(function(){
		lineType = 2;
		$.checkLine();
	})
	//买android线
	$('.android').click(function(){
		lineType = 3;
		$.checkLine();		
	})
	//买iphone5线
	$('.iphone5').click(function(){
		lineType = 1;
		$.checkLine();		
	})	
	//暂不购买跳回公众号首页
	$('.next-buy').click(function(){
		wx.closeWindow();	
	})			

	// $.popTagShow(6,null,null,null,null,null,null,"知道啦！",$.scan);

	$.popTagShow(2,'正在调起扫描','请稍后',null,null,null,null,null,null);

	wx.ready(function(){
		$.scan();
	})	
})